package com.zzyl.common.utils.huawei;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.huaweicloud.sdk.core.auth.AbstractCredentials;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.exception.base.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import static com.zzyl.common.constant.CacheConstants.HUAWEI_IOT_ALL_KEY;

@Slf4j
@Component
public class HuaweiToolUtils {
    @Autowired
    private HuaweiClientUtils clientUtils;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 1.1 从物联网平台同步产品列表
     */
    public void synProduct() {
        //调用生成client对象
        IoTDAClient client = clientUtils.getClient();
        //构建请求
        ListProductsRequest request = new ListProductsRequest();
        //设置条数
        request.setLimit(50);
        try {
            //发出请求
            ListProductsResponse response = client.listProducts(request);
            if (response.getHttpStatusCode() != 200) {
                throw new BaseException("物联网接口 - 查询产品，同步失败");
            }
            List<ProductSummary> products = response.getProducts();
            //新建productVO集合
            List<ProductVo> productVos = BeanUtil.copyToList(products, ProductVo.class);
            redisTemplate.opsForValue().set(HUAWEI_IOT_ALL_KEY, productVos);
        } catch (ConnectionException e) {
            throw new BaseException("iot获取失败");
        }
    }


    /**
     * 新增设备
     *
     * @param deviceDto
     * @param secret
     * @return
     */
    public String addProduct(DeviceDto deviceDto, String secret) {

        IoTDAClient client = clientUtils.getClient();

        //iot中新增设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withProductId(deviceDto.getProductKey());
        body.withDeviceName(deviceDto.getDeviceName());
        body.withNodeId(deviceDto.getNodeId());
        request.withBody(body);
        AuthInfo authInfo = new AuthInfo();

        authInfo.withSecret(secret);
        body.setAuthInfo(authInfo);
        AddDeviceResponse response;
        try {
            response = client.addDevice(request);
            return response.getDeviceId();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }

    }

    /**
     * 删除设备
     *
     * @param iotId
     */
    public void remove(String iotId) {

        IoTDAClient client = clientUtils.getClient();
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        try {
            DeleteDeviceResponse response = client.deleteDevice(request);
        } catch (ConnectionException e) {
            throw new BaseException("删除设备失败");
        }
    }


    /**
     * 查询设备详情
     *
     * @param deviceId
     * @return
     */
    public ShowDeviceResponse queryProduct(String deviceId) {
        IoTDAClient client = clientUtils.getClient();
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(deviceId);
        try {
            ShowDeviceResponse response = client.showDevice(request);
            return response;
        } catch (ConnectionException e) {
            throw new BaseException("查询设备失败");
        }
    }

    /**
     * 查看设备属性
     *
     * @param iotId
     * @return
     */
    public List queryServiceProperties(String iotId) {
        IoTDAClient client = clientUtils.getClient();
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询设备上报数据，调用失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty(shadow)) {
            List<Object> emptyList = Collections.emptyList();
            return emptyList;
        }
        //返回数据
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());

        List<Map<String, Object>> list = new ArrayList<>();

        //处理上报时间日期
        LocalDateTime activeTime = LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        jsonObject.forEach((k, v) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", k);
            map.put("value", v);
            map.put("eventTime", eventTime);
            list.add(map);
        });
        return list;
    }

    /**
     * 修改设备
     */
    public void updateProject(String deviceId, String name) {
        IoTDAClient client = clientUtils.getClient();
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(deviceId);
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(name);
        request.withBody(body);
        try {
            UpdateDeviceResponse response = client.updateDevice(request);
            System.out.println(response.toString());
        } catch (ConnectionException e) {
            throw new BaseException("修改失败");
        }
    }
}
